//
//  ChaoZhuoViewController.m
//  NC-Trendy
//
//  Created by brother on 16/2/24.
//  Copyright © 2016年 liang. All rights reserved.
//

#import "ChaoZhuoViewController.h"

@interface ChaoZhuoViewController ()<UITableViewDataSource,UITableViewDelegate>
///显示所有item的tableView
@property (nonatomic, weak) UITableView *tableView;
///保存所有item的数组
@property (nonatomic, strong) NSMutableArray<NCItem *> *itemArray;
///保存所有item中最大的item_id
@property (nonatomic, assign) NSInteger max_id;
///保存所有item中最小的item_id
@property (nonatomic, assign) NSInteger min_id;
///用于判断是否上拉或下拉刷新
@property (nonatomic, assign) BOOL isTop;
///设置当前控制器的请求类型
@property (nonatomic, copy) NSString *type;
///正在刷新状态
@property (nonatomic, assign) BOOL isRefreshing;
///转圈
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation ChaoZhuoViewController

//初始化并保存请求类型
- (id)initWithType:(NSString *)type {
    if (self = [super init]) {
        self.type = type;
    }
    return self;
}
//懒加载item数组
- (NSMutableArray *)itemArray {
    if (_itemArray == nil) {
        _itemArray = [NSMutableArray array];
    }
    return _itemArray;
}
//懒加载
- (UITableView *)tableView {
    if (_tableView == nil) {
        //创建一个tableView
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, -40, kScreenW, kScreenH) style:UITableViewStyleGrouped];
        //设置代理
        tableView.delegate = self;
        //设置数据源
        tableView.dataSource = self;
        //添加到view
        [self.view addSubview:tableView];
        //保存到属性
        _tableView = tableView;
    }
    return _tableView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //发数据请求到类型
    NSDictionary *dict = @{@"type":self.type};
    self.view.backgroundColor = [UIColor whiteColor];
    
    //读取本地数据库
    NSMutableArray<NCItem *> *itemDBArray = [self loadItemArray];
    
    if (itemDBArray) {
        self.itemArray = itemDBArray;
        //保存最大和最小的item_id
        [self setMinAndMaxItem_id];
        //设置下拉和上拉刷新
        [self setRefreshHeaderAndFooter];
    } else {
        //发送网络请求
        [self sendHttpRequestDict:dict completion:^{
            [self setRefreshHeaderAndFooter];
        }];
    }
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Do any additional setup after loading the view.
}

//读取本地数据库的item
- (NSMutableArray<NCItem *> *)loadItemArray {
    NSMutableArray<CoreItem *> *mutArray = [ItemDBTools itemArrayWithType:self.type withMin_id:[NSString stringWithFormat:@"%ld",(long)self.min_id] errorInfo:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    if (mutArray) {
        NSMutableArray *itemArray = [NSMutableArray array];
        [mutArray enumerateObjectsUsingBlock:^(CoreItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NCItem *item = [ItemDBTools ncItemWithCoreItem:obj];
            [itemArray addObject:item];
        }];
       return itemArray;
    } else {
       return nil;
    }
}

//保存最大和最小的item_id
- (void)setMinAndMaxItem_id {
    //排序
    [self.itemArray sortUsingComparator:^NSComparisonResult(NCItem *_Nonnull obj1, NCItem *_Nonnull obj2) {
        //倒序
        if ([obj2.item_id integerValue] > [obj1.item_id integerValue]) {
            return YES;
        } else {
            return NO;
        }
    }];
    NCItem *min_item = [self.itemArray lastObject];
    self.min_id = [min_item.item_id integerValue];
    NCItem *max_item = [self.itemArray firstObject];
    self.max_id = [max_item.item_id integerValue];
    [self.tableView reloadData];
}

- (void)setRefreshHeaderAndFooter {
    //设置下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //请求头
        NSDictionary *dict = @{@"max_item_id":@(self.max_id),@"type":self.type};
        //是下拉
        self.isTop = YES;
        //发送网络请求
        [self sendHttpRequestDict:dict completion:nil];
        self.isRefreshing = YES;
    }];
    //设置上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //
        self.isTop = NO;
        //读取本地数据库
        NSMutableArray<NCItem *> *itemDBArray = [self loadItemArray];
        if (itemDBArray) {
            [self.itemArray addObjectsFromArray:itemDBArray];
            //保存最大和最小的item_id
            [self setMinAndMaxItem_id];
        } else {
            NSDictionary *dict = @{@"min_item_id":@(self.min_id),@"type":self.type};
            [self sendHttpRequestDict:dict completion:nil];
            self.isRefreshing = YES;
        }
        //
    }];
}

- (void)endRefreshItems {
    if (self.isTop == YES) {
        //停止下拉刷新
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

//发送网络请求时调用
- (void)sendHttpRequestDict:(NSDictionary *)dict completion:(void(^)())completion{
    if (self.isRefreshing == YES) {
        return;
    } else {
        [self.hud show:YES];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        //manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        //url服务器请求接口
        NSString *urlPath = [NSString stringWithFormat:@"%@/%@/%@",Localhost,Article,aNewsItem];
        //发送get请求
        [manager GET:urlPath parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            // NSLog(@"%@",[responseObject class]);
            //判断响应对象是否NSData类型的数据
            if ([responseObject isKindOfClass:[NSData class]]) {
                //解析json
                NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                //判断返回的状态是否成功
                if ([jsonDic[@"status"]isEqualToString:@"1"]) {
                    //数组接收数据
                    NSArray *array = [NSArray arrayWithArray:jsonDic[@"data"]];
                    //遍历
                    [array enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        //初始化item
                        NCItem *item = [[NCItem alloc]initWithDic:obj];
                        //保存到本地数据库
                        [ItemDBTools insertCoreItemWithItem:item errorInfo:^(NSError *error) {
                            NSLog(@"insertItem %@",error);
                        }];
                        //添加到item数组里
                        [self.itemArray addObject:item];
                    }];
                    //保存最大和最小的item_id
                    [self setMinAndMaxItem_id];
                } else {
                    NSLog(@"no data");
                }
            }
            [self.hud hide:YES];
            self.isRefreshing = NO;
            [self endRefreshItems];
            if (completion) {
                completion();
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            self.isRefreshing = NO;
            [self endRefreshItems];
            if (error) {
                //请求失败
                NSLog(@"%@",error);
                [self.hud hide:NO];
            }
            if (completion) {
                completion();
            }
        }];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.itemArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //加载cell
    NCItemCell *cell = [NCItemCell itemCellWithTableView:tableView];
    //设置cell的item
    cell.ncItem = self.itemArray[indexPath.row];
    return cell;
}


#pragma mark - UITableViewDelegate
//
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //拿到cell的item
    NCItem *item = self.itemArray[indexPath.row];
    NSLog(@"wenz id %@",item.article_id);
    //让代理显示的文章
    if ([self.delegate respondsToSelector:@selector(showArticleWithId:)]) {
        [self.delegate showArticleWithId:item.article_id];
    }
}
//cell行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 350;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end



